package cn.myjerry.server.demo2;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Date;
/**
 * 封装response
 * @author Jerry
 */
public class Response {
	public static final String CRLF = "\r\n";
	public static final String BLANK = " ";
	private BufferedWriter bw;
	private StringBuilder headInfo;
	private StringBuilder content;
	private int len;
	public Response() {
		headInfo = new StringBuilder();
		content = new StringBuilder();
		len = 0;
	}
	public Response(OutputStream os) {
		this();
		bw = new BufferedWriter(new OutputStreamWriter(os));
	}
	public Response(Socket client) {
		this();
		try {
			bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
		} catch (IOException e) {
			headInfo = null;
		}
	}
	/**
	 * 构建正文
	 */
	public Response print(String info) {
		content.append(info);
		len += info.getBytes().length;
		return this;
	}
	/**
	 * 构建正文 + 回车
	 */
	public Response println(String info) {
		content.append(info).append(CRLF);
		len += (info + CRLF).getBytes().length;
		return this;
	}
	/**
	 * 构建响应头
	 */
	private void createHeadInfo(int code) {
		headInfo.append("HTTP/1.1 ").append(code).append(BLANK);
		switch(code) {
			case 200:
				headInfo.append("ok");
				break;
			case 404:
				headInfo.append("NOT FOUND");
				break;
			case 500:
				headInfo.append("SERVER ERROR");
				break;
		}
		headInfo.append(CRLF);
		headInfo.append("Server: JERRY").append(CRLF);
		headInfo.append("Date:").append(new Date()).append(CRLF);
		headInfo.append("Content-Type: text/html;charset=UTF-8").append(CRLF);
		headInfo.append("Content-Length:").append(len).append(CRLF);
		headInfo.append(CRLF);
	}
	/*
	 * 推送到客户端
	 */
	void pushToClient(int code) throws IOException {
		if(null == headInfo) {
			code = 500;
		}
		createHeadInfo(code);
		bw.append(headInfo.toString());
		bw.append(content.toString());
		bw.flush();
	}
	public void close() {
		CloseUtil.closeAll(bw);
	}
}
